package com.htu.hdfs;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class HdfsHelper {
	private Configuration conf;
	private FileSystem hdfs;
	private static String __HDFS_PATH = "hdfs://localhost:9000";

	HdfsHelper(){
	}

	HdfsHelper(Configuration conf,FileSystem hdfs){
		this.conf = conf;
		this.hdfs = hdfs;
	}

	void setConf(){
		Configuration conf = new Configuration();
		this.conf = conf;
	}
	
	void initHdfs() throws IOException,URISyntaxException{
		FileSystem fs = FileSystem.get(new URI(__HDFS_PATH), conf);
		this.hdfs = fs;
	}
	
    public boolean MakeDir(String path) throws IllegalArgumentException, IOException{
		boolean result = hdfs.mkdirs(new Path(path));
		return result;
	}
	
	public FSDataOutputStream TouchFile(String path) throws IllegalArgumentException, IOException{
		FSDataOutputStream result = hdfs.create(new Path(path));
		return result;
	}
	
	public class WriteFile {
		 public void main(String[] args) throws IOException {  
		    Configuration conf = new Configuration();  
		  
		    String hdfsPath = "hdfs://localhost:9000";  
		    FileSystem hdfs = FileSystem.get(URI.create(hdfsPath), conf);  
		  
		    String filePath = "/hdfstest/writefile";  
		  
		    FSDataOutputStream create = hdfs.create(new Path(filePath));  
		  
		    System.out.println("Step 1 Finish!");  
		  
		    String sayHi = "hello world hello data!";  
		    byte[] buff = sayHi.getBytes();  
		    create.write(buff, 0, buff.length);  
		    create.close();  
		    System.out.println("Step 2 Finish!");  
		    }
	}

    	public void CopyFromLocalFile(String from_Linux,String to_HDFS) throws IllegalArgumentException, IOException {
		hdfs.copyFromLocalFile(new Path(from_Linux), new Path(to_HDFS));
	}
}